package org.insia.smartposse.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.log4j.Logger;
/**
 * Passeword encoder
 * @author sok hout
 *
 */
public final class PasswordEncoder {

	/**
	 * log4j logger
	 */
	private static Logger logger = Logger.getLogger(PasswordEncoder.class);

	/**
	 * Digest algorithm
	 */
	private final static String ALGORITHM = "SHA1";

	/**
	 * Encode user's password
	 * 
	 * @param password
	 *            Plain password
	 * @return Hashed password
	 */
	public final static String encode(String password) {

		try {
			final MessageDigest sha1 = MessageDigest.getInstance(ALGORITHM);

			sha1.reset();
			sha1.update(password.getBytes());

			return ( byteToHex(sha1.digest()));

		} catch (NoSuchAlgorithmException ex) {
			logger
					.error(ALGORITHM + " algorithm isn't present on the JVM.",
							ex);
		}

		return null;
	}

	/**
	 * Convertit des octets en leur representation hexadecimale (base 16),
	 * chacun se retrouvant finalement 'non signe' et sur 2 caracteres.
	 */
	public static String byteToHex(byte[] bits) {
		if (bits == null) {
			return null;
		}
		StringBuffer hex = new StringBuffer(bits.length * 2); // encod(1_bit)
																// => 2 digits
		for (int i = 0; i < bits.length; i++) {
			if (((int) bits[i] & 0xff) < 0x10) { // 0 < .. < 9
				hex.append("0");
			}
			hex.append(Integer.toString((int) bits[i] & 0xff, 16)); // [(bit+256)%256]^16
		}
		return hex.toString();
	}
}